<template>
  <div id="Goods">
    <!-- 查询区域 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="searchForm.productName" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="上下架">
        <el-select v-model="searchForm.status" placeholder="请选择">
          <el-option label="上架" value="1"></el-option>
          <el-option label="下架" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请选择分类">
        <el-cascader :options="options" @change="handleChange" clearable></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch" class="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="onReset" class="el-icon-refresh">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div style="margin-bottom: 20px;">
      <el-button type="primary" icon="el-icon-plus" @click="onAddProduct">新增商品</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="batchDelete">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="productId" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="imgLink" label="图片" width="80" align="center">
        <template slot-scope="scope">
          <img :src="'/img'+scope.row.imgLink" alt="Icon" style="width: 40px; height: 40px;">
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showDetail(scope.row)">{{ scope.row.name }} <i class="el-icon-view"></i></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="typeId" label="商品类型" align="center">
        <template slot-scope="scope">
          {{ getGoodsTypes(scope.row.typeId) }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" align="center"></el-table-column>
      <el-table-column prop="stock" label="上架库存" align="center"></el-table-column>
      <el-table-column prop="onOff" label="上架/下架" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
              :value="scope.row.onOff === 0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              class="custom-switch"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="onAddStock(scope.$index, scope.row)">+ 添加库存</el-button>
          <el-button size="mini" type="text" @click="onEdit(scope.$index, scope.row)" class="el-icon-edit">修改</el-button>
          <el-button size="mini" type="text" @click="onDelete(scope.$index, scope.row.productId)" class="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
    ></el-pagination>
    <!-- 商品详情弹出层 -->
    <el-dialog :visible.sync="dialogVisible1" width="50%" top="5vh" >
      <div class="goods-detail">
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span>商品详情</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-image :src="'/img'+products.imgLink" fit="contain" style="width: 100%; height: 300px;"></el-image>
            </el-col>
            <el-col :span="16">
              <el-form label-width="120px">
                <el-divider content-position="left">商品信息</el-divider>
                <el-form-item label="编号:">
                  {{ products.productId }}
                </el-form-item>
                <el-form-item label="商品名称:">
                  {{ products.name }}
                </el-form-item>
                <el-form-item label="商品售价:">
                  {{ products.price }}元
                </el-form-item>
                <el-form-item label="上架库存:">
                  {{ products.stock }}
                </el-form-item>
                <el-form-item label="商品单位:">
                  {{ products.unit }}
                </el-form-item>
                <el-form-item label="上架状态:">
                  {{ products.onOff === 'false' ? '上架' : '下架' }}
                </el-form-item>
                <el-divider content-position="left">图片展示</el-divider>
                <el-form-item label="主展示图:">
                  <el-image :src="'/img'+products.imgLink" fit="contain" style="width: 100px; height: 100px;"></el-image>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </el-dialog>

    <!-- 商品修改弹出层 -->
    <el-dialog :visible.sync="dialogVisible2" width="50%" top="5vh" >
      <div class="update-goods">
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span>修改商品信息</span>
          </div>
          <el-form :model="goodsForm" :rules="rules" ref="goodsForm" label-width="120px">
            <el-form-item label="编号" prop="productId">
              <el-input v-model="goodsForm.productId" disabled></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                  <el-form-item label="商品分类" prop="firstCategory">
                    <el-cascader :options="options" @change="handleChange" clearable></el-cascader>
                  </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="goodsForm.name" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model.number="goodsForm.price" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="goodsForm.unit" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item label="上架库存" prop="stock">
              <el-input v-model.number="goodsForm.stock" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item label="展示图" prop="mainImage">
              <el-upload
                  action="https://jsonplaceholder.typicode.com/posts/"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :file-list="goodsForm.mainImageList"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">修改</el-button>
              <el-button @click="quit2">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </el-dialog>

    <!--新增商品弹出层-->
    <el-dialog :visible.sync="dialogVisible3" width="50%" top="5vh">
      <div class="add-goods">
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span>新增商品信息</span>
          </div>
          <el-form :model="addGoodsForm" :rules="addRules" ref="addGoodsForm" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品分类" prop="typeId">
                  <el-cascader :options="options" @change="handleChange2"  clearable></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addGoodsForm.name" style="width: 400px"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model.number="addGoodsForm.price" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="addGoodsForm.unit" style="width: 200px"></el-input>
            </el-form-item>
            <el-form-item label="上架库存" prop="stock">
              <el-input v-model.number="addGoodsForm.stock" style="width: 200px"></el-input>
            </el-form-item>
            <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-change="handleFileChange"
                list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <el-form-item>
              <el-button type="primary" @click="submitAddForm()">添加</el-button>
              <el-button @click="quit3">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Goods",
  data() {
    return {
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      selectedProduct: {},
      searchForm: {
        productName: '',
        status: '',
        firstCategory: '',
        secondCategory: ''
      },
      active: true,
      level1Category:[],
      secondaryCategory:[],
      options:[],
      tableData: [],
      goodsTypes: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      visible: false,
      goodsForm: {
        productId: '',
        name: '',
        price: '',
        unit: '',
        stock: '',
        mainImageList: []
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入上架库存', trigger: 'blur' },
          { type: 'number', message: '库存必须为数字值', trigger: 'blur' }
        ]
      },
      products: {
        productId: '',
        name: '',
        price: '',
        stock: '',
        unit: '',
        status: '',
        imgLink: '',
        mainImage: '',
        subImages: [
        ],
        detailImages: [
        ]
      },
      product: {},
      selectedProducts: [], // 用于存储选中的商品ID
      addGoodsForm: {
        productId: '',
        firstCategory: '',
        name: '',
        price: "",
        unit: '',
        stock: 0,
        typeId:'',
      },
      addRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入上架库存', trigger: 'blur' },
          { type: 'number', message: '库存必须为数字值', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '请选择商品类别', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入商品单位', trigger: 'blur' }
        ]
      },
      dialogImageUrl: '',
      dialogVisible4: false,
      disabled: false,
      fileList:[],
      Types:[]
    };
  },
  methods: {
    //初始化页面
    initTabl() {
      Object.assign(this.searchForm, {"currentPage": this.currentPage, "pageSize": this.pageSize})
      this.$axios.post("http://localhost:8090/product/getAllProduct", this.searchForm).then(({ data }) => {
        console.log(data);
        this.tableData = data.records;
        this.total = data.total;
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '初始化失败!'
        });
      })
    },
    //初始化商品类别
    initGoodsType() {
      this.$axios.get("http://localhost:8090/product-type/getAllGoodsType").then(({ data }) => {
        console.log(data);
        this.goodsTypes = data;
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '初始化失败!'
        });
      })
    },
    getGoodsTypes(id){
      console.log('aa:'+id);
      let type = id.split('-')[1];

      for(let i=0;i<this.Types.length;i++){
        if(this.Types[i].typeId==type){
          return this.Types[i].typeName
        }
      }
    },
    initialTypeSelect: function () {
      this.$axios.get("http://localhost:8090/product-type/getAllProductType?level="+2).then(({ data }) => {
        this.types = data;
      })
      this.$axios.get("http://localhost:8090/product-type/getAllProductType").then(({ data }) => {
        this.Types = data;
      })
    },
    initialTypeSelect2: function () {
      this.$axios.get("http://localhost:8090/product-type/getAllProductType?level="+1).then(({ data }) => {
        this.level1Category = data;
        this.$axios.get("http://localhost:8090/product-type/getAllProductType?level="+2).then(({ data }) => {
          this.secondaryCategory = data;
          this.getOptions(this.level1Category, this.secondaryCategory);
        })
      })

    },
    getOptions(level1Category, secondaryCategory){
      let options = [];
      for (let i = 0; i < level1Category.length; i++) {
        let item = {
          label: level1Category[i].typeName,
          value: level1Category[i].typeId,
          children: []
        }
        for (let j = 0; j < secondaryCategory.length; j++) {
          if (level1Category[i].typeId === secondaryCategory[j].parentId) {
            item.children.push({
              label: secondaryCategory[j].typeName,
              value: secondaryCategory[j].typeId
            })
          }
        }
        options.push(item);
      }
      this.options = options;
    },
    handleChange(value) {
      if (value.length !== 0){
        this.type = value[0] + "-" + value[1];
      }else if (value.length === 0){
        this.type = "";
      }
      this.initTabl()
    },
    handleChange2(value) {
      if (value.length !== 0){
        this.addGoodsForm.typeId = value[0] + "-" + value[1];
      }else if (value.length === 0){
        this.addGoodsForm.typeId = "";
      }
      this.initTabl()
    },
    //点击商品名称弹出商品详情弹出框
    showDetail(row) {
      console.log('详情:', row);
      this.products = row;
      this.dialogVisible1 = true;
    },
    //根据条件查询搜索
    onSearch() {
      this.initTabl();
      console.log('搜索:', this.searchForm);
    },
    //重置按钮
    onReset() {
      this.searchForm = { productName: '', status: '', firstCategory: '', secondCategory: '' };
      this.initTabl();
    },
    //添加库存按钮
    onAddStock(index, row) {
      console.log('添加库存:', index, row);
    },
    //修改商品信息
    onEdit(index, Goods) {
      console.log('修改:', index, Goods);
      this.goodsForm = Goods;
      this.dialogVisible2 = true;
    },
    //删除商品信息
    onDelete(index, productId) {
      console.log('删除:', index, productId);
      this.$confirm('此操作将永久删除选中的商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        //  debugger
        this.$axios.get("http://localhost:8090/product/deleteProduct/" + productId).then(({ data }) => {
          console.log(data);
          if (data){
            this.initTabl();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    //分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.initTabl();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initTabl();
    },
    handleSelectionChange(val) {
      this.selectedProducts = val.map(item => item.productId);
    },
    //批量删除
    batchDelete() {
      if (this.selectedProducts.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的商品!'
        });
        return;
      }

      this.$confirm('此操作将永久删除选中的商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$axios.post("http://localhost:8090/product/batchDeleteProduct", { productIds: this.selectedProducts })
          .then(({ data }) => {
            if (data) {
              this.initTabl();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    quit2 () {
      this.dialogVisible2 = false;
    },
    quit3 () {
      this.dialogVisible3 = false;
    },
    //修改商品信息
    submitForm() {
      console.log('修改商品:', this.goodsForm);
      this.$axios.post("http://localhost:8090/product/updateProduct", this.goodsForm).then(({ data }) => {
        console.log(data)
        if (data) {
          this.dialogVisible2 = false;
          this.initTabl();
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
        }else{
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        }
      })
    },
    //打开新增商品弹窗
    onAddProduct() {
      this.dialogVisible3 = true;
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList;  // 实时同步选择的文件列表
    },
    //新增商品
    submitAddForm() {
      console.log('新增商品:', this.addGoodsForm)
      console.log('新增商品:', this.fileList)
      this.$refs.addGoodsForm.validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.error('请选择商品展示图片');
            return;
          }

          let formData = new FormData();
          formData.append('productId', this.addGoodsForm.productId);
          formData.append('firstCategory', this.addGoodsForm.firstCategory);
          formData.append('name', this.addGoodsForm.name);
          formData.append('price', this.addGoodsForm.price)
          formData.append('typeId', this.addGoodsForm.typeId);
          formData.append('unit', this.addGoodsForm.unit)
          formData.append('stock', this.addGoodsForm.stock);
          formData.append('secondCategory', this.addGoodsForm.secondCategory);

          this.fileList.forEach(file => {
            formData.append('files', file.raw);
          });

          this.$axios.post('/api/product/saveProduct', formData).then(({ data }) => {
            if(data !== null && data !== undefined ){
              this.$notify({
                title: '添加成功',
                message: '添加成功！',
                type: 'success'
              });
              this.initTabl();
              this.dialogVisible3 = false;
              this.resetForm();
              this.$refs.addGoodsForm.resetFields();
              this.fileList = [];
            }
            console.log(data);
          }).catch(error => {
            this.$notify({
              title: '添加失败',
              message: '添加失败，请稍后重试',
              type: 'warning'
            });
            console.log(error);
          });
        } else {
          this.$notify({
            title: '更新失败',
            message: '请检查表单输入是否正确',
            type: 'warning'
          });
          return false;
        }
      });
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(f => f.uid !== file.uid);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePreview(file) {
      console.log(file);
    }
  },
  mounted() {
    this.initGoodsType();
    this.initTabl();
    this.initialTypeSelect()
    this.initialTypeSelect2();
  }

};
</script>

<style scoped>
/* 添加一些样式以确保页面美观 */
.demo-form-inline {
  margin-bottom: 20px;
}
.el-table {
  margin-top: 20px;
}

/* 新增：设置表格单元格内容居中 */
.el-table .cell {
  text-align: center;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.el-table >>> .el-table__header tr th {
  background-color: lightgray;
  color: black;
}
</style>































